const express = require('express');
const router = express.Router();
const db = require('../db');
//注册
//引入utility
const utility = require('utility');
//登录
//引入jwt
const jwt = require('jsonwebtoken');


//注册
router.post('/reg', function (req, res) {

    //给密码加密
    req.body.password = utility.md5(req.body.password);
    // console.log(req.body);
    db('insert into user_user set ?', req.body, function (err, data) {
        console.log(err)
        //         err ?
        //             console.log(err)() :

        if (err != null) {
            res.send({
                status: 1,
                message: '注册失败!'
            })
        } else {
            res.send({
                status: 0,
                message: '注册成功!'
            })
        }
    });
});

//登录
router.post('/login', function (req, res) {

    //引入用户名和密码,对密码加密
    let username = req.body.username;
    let password = utility.md5(req.body.password);
    // req.body.pwd = utility.md5(req.body.pwd);
    //查询
    db('select * from user_user where username=? and password=?', [username, password], function (err, arr) {

        if (err != null) {
            console.log(err);
            res.send({
                status: 1,
                message: '登录失败!'
            });
        } else {
            if (arr.length == 0) {
                res.send({
                    status: 1,
                    message: '用户名或密码错误!'
                });
            } else {
                //生成token
                let id = arr[0].id
                let token = 'Bearer ' + jwt.sign({
                    id: id

                }, 'be139', {
                    expiresIn: '5h'
                });
                res.send({
                    status: 0,
                    message: '登录成功！',
                    token: token
                })
            };
        };
    });
});


module.exports = router